package com.mmlc.utils;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

import com.mmlc.meimei.lichengkongjian.R;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.Callback.CommonCallback;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.image.ImageOptions.Builder;
import org.xutils.x;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class XUtils {

    public abstract class XUtilsDrawableCallback {

        public abstract void onSuccess(Drawable drawable);

        public abstract void onError(Throwable throwable, boolean b);
    }

    public abstract class XUtilsStringCallback {
        Context context;

        public XUtilsStringCallback(Context context) {
            this.context = context;
        }

        public abstract void success(String result);

        /**
         * @param errorCode -1:softNet,-2:shutNet,-3:cancelled
         *                  300:unLogin
         *                  code:message
         */
        public abstract void failure(int errorCode, String errorMsg);

        public void onSuccess(String s) {
            try {
                if (ViewUtils.isEmpty(s)) {
                    failure(-1, "网络不稳定，请稍后再试");
                    return;
                }
                JSONObject json = new JSONObject(s);
                if (json.optInt("code") == 0) {
                    success(s);
                } else if (json.optInt("code") == 300) {
                    failure(300, json.optString("message"));
                    ToastUtils.showToast(json.optString("message"));
//                    context.startActivity(new Intent(context, LoginActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                } else {
                    failure(json.optInt("code"), json.optString("message"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        public void onError(Throwable throwable, boolean b) {
            failure(-1, throwable.getMessage());
            ToastUtils.showToast("网络不稳定，请稍后再试");
        }

        public void onCancelled(Callback.CancelledException e) {
            failure(-3, "users canceled");
        }

    }

    public static Builder getImageOptionsBuilder() {
        return new ImageOptions.Builder()
                .setImageScaleType(ScaleType.CENTER_CROP)
                .setFadeIn(true)
                .setCrop(true)
                .setFailureDrawableId(R.drawable.placeholder);
    }

    /**
     * 图片下载
     */
    public static void loadImage(String imgUrl, CommonCallback<Drawable> commonCallback) {
        loadImage(imgUrl, getImageOptionsBuilder().build(), commonCallback);
    }

    public static void loadImage(String imgUrl, ImageOptions options, CommonCallback<Drawable> commonCallback) {
        x.image().loadDrawable(imgUrl, options, commonCallback);
    }

    /**
     * @param iv     ImageView控件
     * @param imgUrl image地址
     */
    public static void image(ImageView iv, String imgUrl) {
        image(iv, imgUrl, getImageOptionsBuilder().build(), null, null);
    }

    /**
     * @param iv
     * @param imgUrl
     * @param commonCallback 加载回调
     */
    public static void image(ImageView iv, String imgUrl, CommonCallback<Drawable> commonCallback) {
        image(iv, imgUrl, getImageOptionsBuilder().build(), commonCallback);
    }

    public static void image(ImageView iv, String imgUrl, XUtilsDrawableCallback drawableCallback) {
        image(iv, imgUrl, getImageOptionsBuilder().build(), drawableCallback);
    }

    /**
     * @param iv
     * @param imgUrl
     * @param options 图片加载配置
     */
    public static void image(ImageView iv, String imgUrl, ImageOptions options) {
        x.image().bind(iv, imgUrl, options);
    }

    public static void image(ImageView iv, String imgUrl, ScaleType scaleType) {
        x.image().bind(iv, imgUrl, getImageOptionsBuilder().setImageScaleType(scaleType).build());
    }

    public static void image(ImageView iv, String imgUrl, ImageOptions options, CommonCallback<Drawable> commonCallback) {
        x.image().bind(iv, imgUrl, options, commonCallback);
    }

    public static void image(ImageView iv, String imgUrl, ScaleType scaleType, CommonCallback<Drawable> commonCallback) {
        x.image().bind(iv, imgUrl, getImageOptionsBuilder().setImageScaleType(scaleType).build(), commonCallback);
    }

    public static void image(ImageView iv, String imgUrl, ImageOptions options, final XUtilsDrawableCallback drawableCallback) {
        image(iv, imgUrl, options, null, drawableCallback);
    }

    public static void image(ImageView iv, String imgUrl, ImageOptions options, CommonCallback<Drawable> commonCallback, final XUtilsDrawableCallback drawableCallback) {
        x.image().bind(iv, imgUrl, options, commonCallback != null ? commonCallback : (drawableCallback != null ? new CommonCallback<Drawable>() {
            @Override
            public void onSuccess(Drawable drawable) {
                if (drawableCallback != null) drawableCallback.onSuccess(drawable);
            }

            @Override
            public void onError(Throwable throwable, boolean b) {
                if (drawableCallback != null) drawableCallback.onError(throwable, b);
            }

            @Override
            public void onCancelled(CancelledException e) {
                if (drawableCallback != null)
                    drawableCallback.onError(new Throwable("users cancelled"), false);
            }

            @Override
            public void onFinished() {

            }
        } : null));
    }

    public static <T extends Object> void httpPost(Context context, String url, CommonCallback<T> commonCallback) {
        httpPost(context, url, "", commonCallback);
    }

    public static <T extends Object> void httpPost(Context context, String url, XUtilsStringCallback commonCallback) {
        httpPost(context, url, "", commonCallback);
    }

    public static <T extends Object> void httpPost(Context context, String url, JSONObject jsonStr, CommonCallback<T> commonCallback) {
        httpPost(context, url, null, jsonStr.toString(), commonCallback);
    }

    public static <T extends Object> void httpPost(Context context, String url, JSONObject jsonStr, XUtilsStringCallback commonCallback) {
        httpPost(context, url, null, jsonStr.toString(), commonCallback);
    }

    public static <T extends Object> void httpPost(Context context, String url, String paramsStr, CommonCallback<T> commonCallback) {
        httpPost(context, url, null, paramsStr, commonCallback);
    }

    public static <T extends Object> void httpPost(Context context, String url, String paramsStr, XUtilsStringCallback commonCallback) {
        httpPost(context, url, null, paramsStr, commonCallback);
    }

    /**
     * json对象参数 http post请求
     *
     * @param headers   headerMap
     * @param paramsStr json.toSting();
     */
    public static <T extends Object> void httpPost(Context context, String url, Map<String, String> headers, String paramsStr, CommonCallback<T> commonCallback) {
        httpPost(context, url, headers, paramsStr, commonCallback, null);
    }

    public static <T extends Object> void httpPost(Context context, String url, Map<String, String> headers, String paramsStr, XUtilsStringCallback commonCallback) {
        httpPost(context, url, headers, paramsStr, null, commonCallback);
    }

    public static <T extends Object> void httpPost(final Context context, String url, Map<String, String> headers, String paramsStr, CommonCallback<T> commonCallback, final XUtilsStringCallback stringCallback) {
        if (!NetUtils.isConnected(context)) {
            ToastUtils.showToast("请连接网络后重试");

            if (commonCallback instanceof XUtilsStringCallback)
                ((XUtilsStringCallback) commonCallback).failure(-2, "the network is shut");

            return;
        }

        RequestParams params = new RequestParams(url);
        if (headers != null && headers.size() > 0) {
            Set<Map.Entry<String, String>> entries = headers.entrySet();
            Iterator<Map.Entry<String, String>> iterator = entries.iterator();
            if (iterator.hasNext()) {
                Map.Entry<String, String> next = iterator.next();
                params.setHeader(next.getKey(), next.getValue());
            }
        }
        if (!ViewUtils.isEmpty(paramsStr))
            params.setBodyContent(paramsStr);
        x.http().post(params, commonCallback != null ? commonCallback : (stringCallback != null ? new CommonCallback<String>() {
            public void onSuccess(String s) {
                try {
                    if (ViewUtils.isEmpty(s)) {
                        stringCallback.failure(-1, "网络不稳定，请稍后再试");
                        return;
                    }
                    JSONObject json = new JSONObject(s);
                    if (json.optInt("code") == 0) {
                        stringCallback.success(s);
                    } else if (json.optInt("code") == 300) {
                        stringCallback.failure(300, json.optString("message"));
                        ToastUtils.showToast(json.optString("message"));
//                        context.startActivity(new Intent(context, LoginActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                    } else {
                        stringCallback.failure(json.optInt("code"), json.optString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            public void onError(Throwable throwable, boolean b) {
                stringCallback.failure(-1, throwable.getMessage());
                ToastUtils.showToast("网络不稳定，请稍后再试");
            }

            public void onCancelled(Callback.CancelledException e) {
                stringCallback.failure(-3, "users canceled");
            }

            @Override
            public void onFinished() {

            }
        } : null));
    }

    public static <T extends Object> void httpPost(Context context, String url, Map<String, String> paramsStr, CommonCallback<T> commonCallback) {
        httpPost(context, url, null, paramsStr, commonCallback);
    }

    /**
     * map对象参数 http post请求
     *
     * @param headers   headerMap
     * @param paramsStr paramsMap
     */
    public static <T extends Object> void httpPost(Context context, String url, Map<String, String> headers, Map<String, String> paramsStr, CommonCallback<T> commonCallback) {
        if (!NetUtils.isConnected(context)) {
            ToastUtils.showToast("请连接网络后重试");

            if (commonCallback instanceof XUtilsStringCallback)
                ((XUtilsStringCallback) commonCallback).failure(-2, "the network is shut");

            return;
        }

        RequestParams params = new RequestParams(url);
        if (headers != null && headers.size() > 0) {
            Set<Map.Entry<String, String>> entries = headers.entrySet();
            Iterator<Map.Entry<String, String>> iterator = entries.iterator();
            if (iterator.hasNext()) {
                Map.Entry<String, String> next = iterator.next();
                params.setHeader(next.getKey(), next.getValue());
            }
        }
        if (paramsStr != null && paramsStr.size() > 0) {
            Set<Map.Entry<String, String>> entries = paramsStr.entrySet();
            Iterator<Map.Entry<String, String>> iterator = entries.iterator();
            if (iterator.hasNext()) {
                Map.Entry<String, String> next = iterator.next();
                params.addBodyParameter(next.getKey(), next.getValue());
            }
        }
        x.http().post(params, commonCallback);
    }

    public static <T extends Object> void httpGet(String url, CommonCallback<T> commonCallback) {
        httpGet(url, null, commonCallback);
    }

    public static <T extends Object> void httpGet(String url, JSONObject json, CommonCallback<T> commonCallback) {
        RequestParams params = new RequestParams(url);
        if (json != null)
            params.setBodyContent(json.toString());
        x.http().get(params, commonCallback);
    }

    // XUtils.httpPost(getApplicationContext(), Constants.URL_GETCODE, obj, new
    // CommonCallback<String>() {
    // @Override
    // public void onSuccess(String result) {
    // try {
    // L.i(TAG, "URL_GETCODE:" + result);
    //
    // JSONObject json = new JSONObject(result);
    // if ("00000".equals(json.optString("retCode"))) {
    // } else if (json.optString("retCode").equals("20101")) {
    // LogoutUtils.Logout(getApplicationContext());
    // DialogUtils.loginRemind(UserInfoMoreActivity.this);
    // } else if (json.optString("retCode").equals("20102") ||
    // json.optString("retCode").equals("20103")) {
    // LogoutUtils.Logout(getApplicationContext());
    // DialogUtils.informationRemind(UserInfoMoreActivity.this);
    // }
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // }
    //
    // @Override
    // public void onError(Throwable ex, boolean isOnCallback) {
    // App.showNetSoftToast(getApplicationContext());
    // if (ex instanceof HttpException) { // 网络错误
    // HttpException httpEx = (HttpException) ex;
    // int responseCode = httpEx.getCode();
    // String responseMsg = httpEx.getMessage();
    // String errorResult = httpEx.getResult();
    // // ...
    // L.e(TAG, "URL_GETCODE:error=" + responseCode + "/" + "errorMsg=" +
    // responseMsg + "/errorResult:" + errorResult);
    // } else { // 其他错误
    // // ...
    // }
    // }
    //
    // @Override
    // public void onCancelled(CancelledException cex) {
    // }
    //
    // @Override
    // public void onFinished() {
    // }
    // });
}
